package com.quan.sso.client.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;
import com.quan.common.utils.CookieUtils;
import com.quan.sso.common.contants.SSOConfig;
import com.quan.sso.common.pojo.SSOUser;
import com.quan.sso.common.tools.UserHolder;

public class SSOFilter implements Filter {

	//private Logger logger = LoggerFactory.getLogger(this.getClass());

	// 不需要拦截的URI请求
	private String excludes;
	// 不需要拦截的域名
	private String excludesDomain;
	// 服务器公网访问地址
	private String serverBaseUrl;
	// 业务系统与SSO系统间通信的内网地址
	private String serverInnerAddress;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.excludes = filterConfig.getInitParameter("excludes");
		this.excludesDomain = filterConfig.getInitParameter("excludesDomain");
		this.serverBaseUrl = filterConfig.getInitParameter("serverBaseUrl");
		this.serverInnerAddress = filterConfig.getInitParameter("serverInnerAddress");

		if (serverBaseUrl == null || serverInnerAddress == null) {
			throw new ServletException("SSOFilter配置错误，必须配置serverBaseUrl和serverInnerAddress");
		}

		TokenManager.serverInnerAddress = serverInnerAddress;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		response.setContentType("application/json;charset=utf-8");
		response.setStatus(HttpStatus.OK.value());

		//logger.debug("SSOFilter，当前请求URL:{}", request.getRequestURL());

		// 不需要拦截的域名，直接通过
		if (excludeDomain(request)) {
			chain.doFilter(request, response);
			return;
		}
		// 不需要拦截的请求，直接通过
		if (requestIsExclude(request)) {
			chain.doFilter(request, response);
			return;
		}

		// 进行登录状态验证
		String token = CookieUtils.getCookieValue(request, SSOConfig.SSO_TOKEN);
		if (null != token && !StringUtils.isEmpty(token)) {
			SSOUser user = null;

			try {
				user = TokenManager.validate(token);
			} catch (Exception e) {

				PrintWriter out = response.getWriter();

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
				map.put("msg", e.getMessage());
				out.print(JSON.toJSONString(map));
				return;
			}

			if (user != null) {
				holdUser(user, request); // 将user存放，供业务系统使用
				CookieUtils.setCookie(request, response, SSOConfig.SSO_TOKEN, token, SSOConfig.TIMEOUT);
				chain.doFilter(request, response); // 请求继续向下执行
			} else {
				CookieUtils.deleteCookie(request, response, SSOConfig.SSO_TOKEN); // 删除无效的Token

				response.setStatus(HttpStatus.OK.value());
				PrintWriter out = response.getWriter();

				Map<String, Object> map = new HashMap<String, Object>();
				// 返回登录超时状态码
				map.put("status", 412);
				map.put("msg", "登录超时或未登录");
				out.print(JSON.toJSONString(map));
				return;
			}

		} else {
			response.setStatus(HttpStatus.OK.value());
			PrintWriter out = response.getWriter();

			Map<String, Object> map = new HashMap<String, Object>();
			// 返回登录超时状态码
			map.put("status", 412);
			map.put("msg", "登录超时或未登录111");
			out.print(JSON.toJSONString(map));
			return;
		}

	}

	@Override
	public void destroy() {

	}

	// 将User存入threadLocal和request中，供业务系统使用
	private void holdUser(SSOUser user, ServletRequest request) {
		UserHolder.setUser(user, request);
	}

	/**
	 * 判断请求是否不需要拦截<br>
	 * 如不需要拦截的请求，在Filter中配置如下正则表达式 ^/((about$)|(contact$)|(notmember/.+))
	 * 
	 * @param request
	 * @return
	 */
	private boolean requestIsExclude(HttpServletRequest request) {
		// 没有设定excludes是，所有经过filter的请求都需要被处理
		if (StringUtils.isEmpty(excludes)) {
			return false;
		}

		// 获取去除context path后的请求路径
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.substring(contextPath.length());

		Pattern p = Pattern.compile(excludes);
		Matcher m = p.matcher(uri);
		// 正则表达式匹配URI被排除，不需要拦截
		boolean isExcluded = m.find();
		if (isExcluded) {
			// logger.debug("该请求地址不需登录即可访问(但权限验证和操作日志记录拦截器无法获取当前用户 ): {}", uri);
		}

		return isExcluded;
	}

	public boolean excludeDomain(HttpServletRequest request) {

		// 没有设定excludes时，所有经过拦截器的请求都需要被处理
		if (StringUtils.isEmpty(excludesDomain)) {
			return false;
		}

		// 获取当前请求域名
		String serverName = request.getServerName();

		Pattern p = Pattern.compile(excludesDomain);
		Matcher m = p.matcher(serverName);
		// 正则表达式匹配URI被排除，不需要拦截
		boolean isExcluded = m.find();
		if (isExcluded) {
			//logger.debug("无需拦截的域名==>{}", serverName);
		}

		return isExcluded;
	}

}
